package com.bigcat.gulimall.demo.test;

import com.alibaba.fastjson.JSON;

import java.awt.geom.Path2D;
import java.util.List;

/**
 * @author sufer_yuan
 * @since 2021/12/23
 * [{"lon":120.210107,"lat":30.174951},{"lon":120.211153,"lat":30.174918},{"lon":120.21118,"lat":30.174125},{"lon":120.210096,"lat":30.174199},{"lon":120.210086,"lat":30.174204},{"lon":120.210086,"lat":30.174204},{"lon":120.210086,"lat":30.174204}]
 * [{"lon":120.210558,"lat":30.174494},{"lon":120.210579,"lat":30.174698},{"lon":120.210622,"lat":30.17416},{"lon":120.210971,"lat":30.174258},{"lon":120.210874,"lat":30.174666},{"lon":120.21066,"lat":30.174694},{"lon":120.210649,"lat":30.17467}]
 * [{"lon":120.210016,"lat":30.175296},{"lon":120.210112,"lat":30.174151},{"lon":120.211051,"lat":30.173724},{"lon":120.211706,"lat":30.174183},{"lon":120.211952,"lat":30.174745},{"lon":120.211598,"lat":30.175185},{"lon":120.211142,"lat":30.175361},{"lon":120.210745,"lat":30.175412}]
 */
public class test2 {
    public static void main(String[] args) {
        String str = "[{\"lon\":120.210086,\"lat\":30.174881},{\"lon\":120.211121,\"lat\":30.174844},{\"lon\":120.211175,\"lat\":30.174148},{\"lon\":120.210021,\"lat\":30.174246},{\"lon\":120.210086,\"lat\":30.174863},{\"lon\":120.210086,\"lat\":30.174863}]";
        long l = System.currentTimeMillis();
        boolean point = isPoint(str, 120.21028967809687, 30.174261515813253);
        long l1 = System.currentTimeMillis();
        System.out.println("结果：======================================》" + point + "   time:  " + (l1 - l));
    }

    /**
     * 使用Path2D创建一个多边形
     *
     * @param polygon 经纬度 集合
     * @return 返回Path2D.Double
     */
    private static Path2D.Double create(List<ScopeRequest> polygon) {

        //创建path2D对象
        Path2D.Double generalPath = new Path2D.Double();

        //获取第一个起点经纬度的坐标
        ScopeRequest first = polygon.get(0);

        //通过移动到以double精度指定的指定坐标，把第一个起点添加到路径中
        generalPath.moveTo(first.getLon(), first.getLat());

        //把集合中的第一个点删除防止重复添加
        polygon.remove(0);

        //循环集合里剩下的所有经纬度坐标
        for (ScopeRequest d : polygon) {
            //通过从当前坐标绘制直线到以double精度指定的新指定坐标，将路径添加到路径。
            //从第一个点开始，不断往后绘制经纬度点
            generalPath.lineTo(d.getLon(), d.getLat());

        }

        // 最后要多边形进行封闭，起点及终点
        generalPath.lineTo(first.getLon(), first.getLat());

        //将直线绘制回最后一个 moveTo的坐标来关闭当前子路径。
        generalPath.closePath();

        return generalPath;

    }

    /**
     * 判断点是否在区域内
     *
     * @param polygon   区域经纬度json字符串
     * @param longitude 经度
     * @param latitude  纬度
     * @return 返回true跟false
     */
    public static boolean isPoint(String polygon, Double longitude, Double latitude) {
        //将json转换成对象
        List<ScopeRequest> list = JSON.parseArray(polygon, ScopeRequest.class);

        Path2D path2D = create(list);
        //true如果指定的坐标在Shape边界内; 否则为false 。
        return path2D.contains(longitude, latitude);

    }
}
